//
//  NetWorkManager.m
//  CToolBox
//
//  Created by SC on 16/12/13.
//  Copyright © 2016年 SC. All rights reserved.
//

#import "NetWorkManager.h"
#import <AVFoundation/AVAsset.h>
#import <AVFoundation/AVAssetExportSession.h>
#import <AVFoundation/AVMediaFormat.h>


static NetWorkManager *sharedInstance = nil;

@interface NetWorkManager()

@end


@implementation NetWorkManager

#pragma mark - sharedInstanceMethod

+ (NetWorkManager *)sharedInstanceMethod
{
    if(sharedInstance == nil){
        static dispatch_once_t onceToken;
        dispatch_once(&onceToken, ^{
            sharedInstance = [[super allocWithZone:NULL]init];
        });
    }
    return sharedInstance;
}

- (instancetype)init
{
    self = [super init];
    if (self) {
//        sharedInstance.taskDic = [[NSMutableDictionary alloc] init];
    }
    return self;
}

+ (id)allocWithZone:(struct _NSZone *)zone
{
    return [NetWorkManager sharedInstanceMethod];
}

- (id)copy
{
    return [NetWorkManager sharedInstanceMethod];
}


#pragma mark - 网络请求的get方法

+ (NSURLSessionDataTask *)getWithUrl:(NSString *)url
            params:(id)params
               tag:(id)tag
      successBlock:(requestSuccess)successBlock
      failureBlock:(requestFailure)failureBlock
{
    AFHTTPSessionManager *session = [NetWorkManager getSessionManager];
    if ([url hasSuffix:@"readTopic"]) {
        session = [NetWorkManager getHtmlSessionManager];
    }
    NSURLSessionDataTask *task = [NetWorkSession requestWithManager:session url:url params:params type:GET successBlock:^(NSDictionary *dictObject) {
        if(successBlock){
            successBlock(dictObject);
        }
    } failureBlock:^(NSError *error) {
        if(failureBlock){
            failureBlock(error);
            NSLog(@"error.userInfo=%@",error.userInfo);
        }
    }];
    
    
    return task;
    
}

#pragma mark - 网络请求的post方法

+ (NSURLSessionDataTask *)postWithUrl:(NSString *)url
             params:(id)params
                tag:(id)tag
       successBlock:(requestSuccess)successBlock
       failureBlock:(requestFailure)failureBlock
{
    NSURLSessionDataTask *task = [NetWorkSession requestWithManager:[NetWorkManager getSessionManager] url:url params:params type:POST successBlock:^(NSDictionary *dictObject) {
        if(successBlock){
            successBlock(dictObject);
        }
    } failureBlock:^(NSError *error) {
        if(failureBlock){
            failureBlock(error);
            NSLog(@"error.userInfo = %@",error.userInfo);
        }
    }];
    
    return task;
    
}

/**
 *  网络请求的实例方法--post上传JOSN
 *
 *  @param url    请求的地址
 *  @param params    请求的参数
 *  @param tag          标示
 *  @param successBlock 请求成功的回调
 *  @param failureBlock 请求失败的回调
 */
+ (NSURLSessionDataTask *)postUploadJOSNWithUrl:(NSString *) url
                                         params:(id) params
                                            tag:(id)tag
                                   successBlock:(requestSuccess) successBlock
                                   failureBlock:(requestFailure) failureBlock
{
    NSURLSessionDataTask *task = [NetWorkSession requestWithManager:[NetWorkManager getSessionUploadJSONManager] url:url params:params type:POST successBlock:^(NSDictionary *dictObject) {
        if(successBlock){
            successBlock(dictObject);
        }
    } failureBlock:^(NSError *error) {
        if(failureBlock){
            failureBlock(error);
            NSLog(@"error.userInfo = %@",error.userInfo);
        }
    }];
    
    return task;
    
}

#pragma mark - 上传图片

+ (void)uploadImageWithHost:(NSString *)host
                    parames:(NSDictionary *)parames
                  imageData:(NSData *)imageData
                       name:(NSString *)name
                   fileName:(NSString *)fileName
                   complete:(void(^)(NSString* url))complete
                    failure:(void(^)(NSError *error))failure
{
    
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json",
                                                         @"text/json",
                                                         @"text/javascript",
                                                         @"text/html",
                                                         @"text/css",
                                                         @"text/plain",
                                                         nil];
    
    manager.requestSerializer=[AFJSONRequestSerializer serializer];
    [manager.requestSerializer setValue:@"multipart/form-data;" forHTTPHeaderField:@"Content-Type"];
    
    [manager POST:host parameters:parames constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        
        [formData appendPartWithFileData:imageData name:name fileName:fileName mimeType:@"image/jpeg"];
        
    } progress:^(NSProgress * _Nonnull uploadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        NSString * imageUrl = [NSString stringWithFormat:@"%@/%@", imageCDNHost, fileName];
        if(complete){
            complete(imageUrl);
        }
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
        NSLog(@"%@",error);
        if(failure){
            failure(error);
        }
    }];
}

+ (void)uploadFileWithHost:(NSString *)host
                   parames:(NSDictionary *)parames
                  fileData:(NSData *)fileData
                      name:(NSString *)name
                  fileName:(NSString *)fileName
                  fileType:(NSString *)fileType
                  complete:(void(^)(NSString* url))complete
                   failure:(void(^)(NSError *error))failure{
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json",
                                                         @"text/json",
                                                         @"text/javascript",
                                                         @"text/html",
                                                         @"text/css",
                                                         @"text/plain",
                                                         nil];
    
    manager.requestSerializer=[AFJSONRequestSerializer serializer];
    [manager.requestSerializer setValue:@"multipart/form-data;" forHTTPHeaderField:@"Content-Type"];
    
    [manager POST:host parameters:parames constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        
        [formData appendPartWithFileData:fileData name:name fileName:fileName mimeType:fileType];
        
    } progress:^(NSProgress * _Nonnull uploadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        NSString * fileUrl = [NSString stringWithFormat:@"%@/%@", imageCDNHost, fileName];
        if(complete){
            complete(fileUrl);
        }
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
        NSLog(@"%@",error);
        if(failure){
            failure(error);
        }
    }];
    
}

+(NSURLSessionTask *)downloadWithManager:(NSString *)url pathString:(NSString *)pathString successBlock:(downloadSuccess)successBlock progressBlock:(downloadProgress) progressBlock{
    
    NSURLRequest * urlRequest = [NSURLRequest requestWithURL:[NSURL URLWithString:url]];
    NSURLSessionConfiguration * configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
    AFURLSessionManager * manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:configuration];
    
    NSURLSessionDownloadTask *downloadTask = [manager downloadTaskWithRequest:urlRequest progress:^(NSProgress * _Nonnull downloadProgress) {
        NSLog(@"%zd , %zd",downloadProgress.completedUnitCount , downloadProgress.totalUnitCount);
        CGFloat progressVale = 1.0 * downloadProgress.completedUnitCount / downloadProgress.totalUnitCount;
        progressBlock(progressVale);
        
    } destination:^NSURL * _Nonnull(NSURL * _Nonnull targetPath, NSURLResponse * _Nonnull response) {
        
        return [NSURL fileURLWithPath:pathString];
        
    } completionHandler:^(NSURLResponse * _Nonnull response, NSURL * _Nullable filePath, NSError * _Nullable error) {
        if (!error) {
            NSLog(@"下载完成");
            successBlock(filePath);
        }
       
    }];
    
    [downloadTask resume];
    
    return downloadTask;
}



+ (AFHTTPSessionManager *)getSessionManager
{
    static AFHTTPSessionManager *manager = nil;
    
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        manager = [[AFHTTPSessionManager alloc] initWithBaseURL:[NSURL URLWithString:kBaseUrl]];
        manager.requestSerializer = [AFHTTPRequestSerializer serializer];
        manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript",@"text/html",@"text/css",@"text/plain", nil];
        manager.requestSerializer.timeoutInterval = 10;
//        [manager.requestSerializer setValue:@"multipart/form-data;" forHTTPHeaderField:@"Content-Type"];
        [manager.requestSerializer setHTTPShouldHandleCookies:YES];
    });
    
    return manager;
    
}

+ (AFHTTPSessionManager *)getHtmlSessionManager{
    static AFHTTPSessionManager *manager = nil;
    
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        manager = [[AFHTTPSessionManager alloc] initWithBaseURL:[NSURL URLWithString:kBaseUrl]];
        manager.requestSerializer=[AFJSONRequestSerializer serializer];
        manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript",@"text/html",@"text/css",@"text/plain", nil];
        manager.responseSerializer = [AFHTTPResponseSerializer serializer];
        manager.requestSerializer.timeoutInterval = 10;
        //[manager.requestSerializer setValue:@"multipart/form-data;" forHTTPHeaderField:@"Content-Type"];
        [manager.requestSerializer setHTTPShouldHandleCookies:YES];
    });
    
    return manager;
    
}
// 上传JSON
+ (AFHTTPSessionManager *)getSessionUploadJSONManager
{
    static AFHTTPSessionManager *manager = nil;
    
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        manager = [[AFHTTPSessionManager alloc] initWithBaseURL:[NSURL URLWithString:kBaseUrl]];
        manager.requestSerializer = [AFJSONRequestSerializer serializer];
        manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript",@"text/html",@"text/css",@"text/plain", nil];
        manager.requestSerializer.timeoutInterval = 10;
        //        [manager.requestSerializer setValue:@"multipart/form-data;" forHTTPHeaderField:@"Content-Type"];
        [manager.requestSerializer setHTTPShouldHandleCookies:YES];
    });
    
    return manager;
    
}

#pragma mark - 取消网络请求
//取消所有的网络请求
+ (void)cancelAll
{
    [[NetWorkManager getSessionManager].operationQueue cancelAllOperations];
}

@end
